package com.ylxn.elasticsearch;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

/**
 * @author: coll man
 * @create: 2021-05-25 17:26
 */
public class ES_User {
    public static void main(String[] args) throws Exception {
        RestHighLevelClient levelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));

        IndexRequest request = new IndexRequest();
        request.index("user").id("1001");
        User user = new User();
        user.setName("zhangsan");
        user.setSex("man");
        user.setAge(11);
        ObjectMapper mappers = new ObjectMapper();
        String value = mappers.writeValueAsString(user);
        //将json放入请求中
        request.source(value, XContentType.JSON);
        //响应值
        IndexResponse response = levelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult());
        levelClient.close();
    }
}
